package co.yixiang.modules.shop.rest;

import cn.hutool.core.util.StrUtil;
import co.yixiang.aop.log.Log;
import co.yixiang.exception.BadRequestException;
import co.yixiang.modules.shop.domain.YxProductBase;
import co.yixiang.modules.shop.domain.YxStoreCategory;
import co.yixiang.modules.shop.domain.YxSupplier;
import co.yixiang.modules.shop.service.YxSupplierService;
import co.yixiang.modules.shop.service.dto.YxStoreCategoryDTO;
import co.yixiang.modules.shop.service.dto.YxStoreCategoryQueryCriteria;
import co.yixiang.modules.shop.service.dto.YxSupplierQueryCriteria;
import co.yixiang.modules.shop.utils.IOUtil;
import co.yixiang.utils.FileUtil;
import co.yixiang.utils.OrderUtil;
import co.yixiang.utils.SecurityUtils;
import co.yixiang.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author frq
 * @date 2020-06-09
 */
@Slf4j
@RestController
@RequestMapping("api")
@Api(value = "供应商管理", description = "供应商管理")
public class YxSupplierController {

    @Autowired
    private YxSupplierService yxSupplierService;

    @Log("查询供应商")
    @ApiOperation(value = "查询供应商")
    @GetMapping(value = "/yxSupplier")
    public ResponseEntity getYxSupplier(YxSupplierQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity(yxSupplierService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("不分页查询供应商")
    @GetMapping("/yxSupplier/getListAll")
    public ResponseEntity getListAll(YxSupplierQueryCriteria criteria) {
        return new ResponseEntity(yxSupplierService.queryAll(criteria), HttpStatus.OK);
    }

    @Log("根据编码查询供应商")
    @GetMapping("/yxSupplier/findByCode/{code}")
    public ResponseEntity findByCode(@PathVariable String code) {
        YxSupplier supplier = yxSupplierService.findByCode(code);
        return new ResponseEntity(supplier, HttpStatus.OK);
    }

    @Log("新增供应商")
    @ApiOperation(value = "新增供应商")
    @PostMapping(value = "/yxSupplier")
    public ResponseEntity create(@Validated @RequestBody YxSupplier resources) {
        return new ResponseEntity(yxSupplierService.create(resources), HttpStatus.CREATED);
    }

    @Log("修改供应商")
    @ApiOperation(value = "修改供应商")
    @PutMapping(value = "/yxSupplier")
    public ResponseEntity update(@Validated @RequestBody YxSupplier resources) {
        yxSupplierService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除供应商")
    @ApiOperation(value = "删除供应商")
    @DeleteMapping(value = "/yxSupplier/{ids}")
    public ResponseEntity delete(@PathVariable Integer ids[]) {
        yxSupplierService.delete(ids);
        return new ResponseEntity(HttpStatus.OK);
    }

    @Log("导入供应商")
    @PostMapping("/yxSupplier/importSupplierApi")
    @ApiOperation(value = "导入供应商")
    public ResponseEntity doImportData(@RequestParam("file") MultipartFile file) {
        List<List<String>> list = new ArrayList<List<String>>();
        String filaName = file.getOriginalFilename();// 获取文件名
        String prefix = filaName.substring(filaName.lastIndexOf(".") + 1);// 获取文件后缀
        Map<String, Object> map = new HashMap<>(2);
        map.put("errno", 0);
        map.put("msg", "导入失败");
        try {
            InputStream in = file.getInputStream();
            if ("xlsx".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsxByType(in);// 导入xlsx格式
            } else if ("xls".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsByType(in);// 导入xls格式
            }
            if (list != null && list.size() > 0) {
                for (List<String> li : list) {
                    if (li.get(0) != null) {
                        //查询导入的供应商是否存在，如果存在更新供应商
                        YxSupplier yxSupplier = yxSupplierService.findByCode(li.get(0));
                        if (yxSupplier == null) {
                            yxSupplier = new YxSupplier();
                        }
                        yxSupplier.setCode(li.get(0)); /**编码*/
                        yxSupplier.setName(li.get(1)); /**名称*/
                        yxSupplier.setRunType(li.get(2));/**经营方式*/
                        yxSupplier.setArea(li.get(3));/**区域*/
                        yxSupplier.setContactor(li.get(4));/**联系人*/
                        yxSupplier.setTel(li.get(5)); /**电话*/
                        yxSupplier.setPhone(li.get(6));/**手机*/
                        yxSupplier.setFax(li.get(7));/**传真*/
                        yxSupplier.setAddress(li.get(8)); /**地址*/
                        yxSupplier.setBankName(li.get(9));/**开户行*/
                        yxSupplier.setBankAccount(li.get(10));/**银行账号*/
                        yxSupplierService.create(yxSupplier);
                    }
                    map.put("errno", 1);
                    map.put("msg", "导入成功");
                }
            } else {
                map.put("msg", "导入文件是空文件，请重新导入");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "读取文件异常,请检查文件数据内容或请联系管理员");
        }

        return new ResponseEntity(map, HttpStatus.CREATED);
    }

    /**
     * 下载模版
     *
     * @param response
     * @throws IOException
     */
    @Log("下载模版")
    @GetMapping("/yxSupplier/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("编码", "A001");
        map.put("名称", "怡亚通");
        map.put("经营方式", "购销");
        map.put("区域编码", "深圳");
        map.put("联系人", "");
        map.put("电话", "");
        map.put("手机", "");
        map.put("传真", "");
        map.put("地址", "");
        map.put("开户行", "");
        map.put("帐号", "");
        map.put("默认扣率", "");
        map.put("所属分店编码", "");
        list.add(map);
        FileUtil.downloadExcel(list, response);
    }
}
